/**
 * Created by yangfan on 2016/12/28.
 */
define(['config/appregister',
    "i18n",
    "business/services/httpServices",
    "business/services/utils",
    "business/home/services/filterService",
    "business/services/filter"], function (app, i18n, httpService,utils) {
    app.controller("searchDataCtrl", function ($scope, $state,DetailFilter,$q,$rootScope) {
        $scope.$parent.isDetailPage = false;
        $scope.$parent.isMainpage = true;
        $scope.i18n = i18n;
        $scope.curFileType = "";
        //点击登录
        $scope.login = function(){
            $state.go("login");
        };


        //导航页面跳转
        $scope.stateGoTo = function (state){
            if(!state)return ;
            $state.go(state);
        };
        //点击全部 数据模板
        $scope.Model = {
            title: {
                domesticData: "",
                interData: ""
            },
            domesticCategory: {
                dataClassify: {
                    i18n: $scope.i18n.dataClassify,
                    content: "",
                    show: false
                },
                fileType: {
                    i18n: $scope.i18n.fileType
                }
            },
            internCategory: {
                dataClassify: {
                    i18n: $scope.i18n.dataClassify
                },
                fileType: {
                    i18n: $scope.i18n.fileType
                }
            },
            list:""
        };
        $scope.fileType = "";
        //详情列表参数
        $scope.listParams = {
            currentTcId: "",
            download: false,
            time: true,
            pageNo: 1,
            pageSize: 10,
            all: false,
            //默认文件格式 全部
            typeId: 0,
            scId: "",
            dcId: "",
            keyWord:"",
            //dcName scName 用于加入缓存 在详情中显示面包树导航
            dcName:"",
            scName:""
        };
        //Analysis Filel Type
        function countFiletype(type) {
            if (type.typeName == "DOC") {
                return "them/img/pdf.png"
            }
        }

        //获取列表数据
        function getlist() {
            var req = {
                type: "GET",
                data: {
                    scId: $scope.listParams.scId,
                    dcId: $scope.listParams.dcId,
                    tcId: $scope.listParams.currentTcId,
                    download: $scope.listParams.download,
                    time: $scope.listParams.time,
                    typeId: $scope.listParams.typeId,
                    pageNo: $scope.listParams.pageNo,
                    pageSize: $scope.listParams.pageSize,
                    all: $scope.listParams.all,
                    keyWord:$scope.listParams.keyWord,
                    dctype:$scope.listParams.dcType
                }
            };
            //国际分类 需要新增 dcType 用于全部选项查询功能

            //在求list 集合方法中 使用scId 来判断 当前的dctype 值。
            if($scope.listParams.currentTcId == 2){
                req.data.dctype =getDcType ($scope.listParams.currentTcId);
            }

            httpService.getList(req).success(function (response) {
                var listData = response.data.list;
                $scope.listModel = [];
                for (var i = 0; i < listData.length; i++) {
                    var obj = {
                        fileId:listData[i].fileId,
                        title: listData[i].name,
                        fileSize: listData[i].size,
                        totalDowns: listData[i].downloadCount + "次",
                        uploader: "Mr Lunix",
                        uploadTime: listData[i].uploadTime,
                        label: listData[i].tagList,
                        //typeUrl: countFiletype(listData[i].type),
                        integral: listData[i].price,
                        typeId:listData[i].typeId
                    };
                    $scope.listModel.push(obj);
                }
                var totalCount = response.data.Pagination.totalCount;
                $scope.$apply(function(){
                    $scope.Model.list = $scope.listModel;
                    $scope.Model.listNum = $scope.listModel.length;
                    $scope.totalItem = totalCount;
                    getListModel()
                })
            }).error(function (data) {

            });
        }
        function getDcType (scId){
            var dcType = [];
            if( $scope.listParams.scId ==15){
                if($scope.interDetailShow.major){
                    dcType.push(1);
                }
                if($scope.interDetailShow.content){
                    dcType.push(2);
                }
                if($scope.interDetailShow.projectPattern){
                    dcType.push(3);
                }
                return dcType.join(",");
            }else if( $scope.listParams.scId ==16){
                if($scope.interDetailShow.major){
                    dcType.push(4);
                }
                if($scope.interDetailShow.content){
                    dcType.push(5);
                }
                if($scope.interDetailShow.projectPattern){
                    dcType.push(6);
                }
                return dcType.join(",");
            }else  if( $scope.listParams.scId ==17){
                if($scope.interDetailShow.major){
                    dcType.push(7);
                }
                if($scope.interDetailShow.content){
                    dcType.push(8);
                }
                if($scope.interDetailShow.projectPattern){
                    dcType.push(9);
                }
                return dcType.join(",");
            }else {
                return "";
            }

        }
        //后台加载的list数据
        $scope.list = [];
        function getListModel(){
            $scope.paginationConf = {
                currentPage: $scope.listParams.pageNo,
                totalItems: $scope.totalItem,
                //每页预览条数
                itemsPerPage:$scope.listParams.pageSize,
                //分页总数
                numberOfPages:Math.ceil($scope.totalItem/$scope.listParams.pageSize),
                // 实际分页长度
                pagesLength:5,
                perPageOptions: [10, 20, 30, 40, 50],
                onChange: function (currentPage) {
                    if(currentPage){
                        $scope.paginationConf.currentPage = currentPage;
                    }
                    $scope.list = [];
                    $scope.listParams.pageNo = $scope.paginationConf.currentPage;
                    getlist()
                }
            };
        };
        //获取三级分类
        function getDetailCategory(req3) {
            var defer = $q.defer();
            httpService.getDetailCategory(req3).success(function (response) {
                if(!response.data){
                    return
                }
                $scope.$apply(function () {
                    if ($scope.listParams.currentTcId == 1) {
                        var objtemp = {
                            dcId:null,
                            dcName:"全部",
                            scId:"",
                            sequence:0
                        };
                        response.data.unshift(objtemp);
                        $scope.detailNationCategory = response.data;
                        defer.resolve(response.data);
                    } else if ($scope.listParams.currentTcId == 2) {
                        //通过DetailFilter 服务 得到三种模式分类数据
                        $scope.detailInternCategory=DetailFilter.getDetail( response.data);
                        defer.resolve($scope.detailInternCategory);
                    }
                });
                if(!$scope.curParams){
                    $scope.listParams.dcId = null;
                    getlist();
                }
            }).error(function (response) {
                defer.reject();
            });
            return defer.promise
        }

        //获取工程资料库文件格式数据
        function getFileType() {
            var reqFile = {
                type: "GET"
            };
            httpService.getFileType(reqFile).success(function (response) {
                $scope.fileType = response.data;
                // $scope.isShow.allTypeUnderLine = true;
            });
        }

        //获取下载排行数据
        function getDownLoadRank() {
            var req = {
                type: "GET",
                count: 6,
                data:{
                    mold:0
                }
            };
            httpService.getDownLoadRank(req).success(function (response) {
                if (!response.data) {
                    return
                }
                $scope.downloadRank = response.data;
            }).error(function () {
            })
        }

        //获取相关资讯分类
        function getKeyWord() {
            if (!$scope.listParams.typeId) {
                //  $scope.listParams.typeId = 1;
            };
            var req = {
                type: "GET",
                data: {
                    count: 6
                },
                uri:"getKeyWord"
            };
            httpService.getKeyWord(req).success(function (response) {
                if (!response.data) {
                    return
                }
                $scope.getKeyWord = response.data;
            }).error(function () {
            })
        }


        //获取页面初始化分级菜单及列表数据
        function loadData(type) {
            //获取文件格式数据
            getFileType();
            //发送请求 获取工程资料库资料分类数据
            var requestion = {
                type: "GET",
                param: "getTopCategory"
            };
            httpService.getTopCategory(requestion).success(function (response) {
                if (response.msg !== "success") {
                    return
                }

                //  得到 一级分类 分类名
                $scope.Model.title.domesticData = response.data[0];
                $scope.Model.title.interData = response.data[1];
                var index = 0;
                if (type == "nation") {
                    index = 0;
                } else if (type == "intern") {
                    index = 1;
                }
                $scope.listParams.currentTcId = response.data[index].tcId;
                var req2 = {
                    type: "GET",
                    tcId: $scope.listParams.currentTcId,
                    param: 'getSecondaryCategory'
                };
                httpService.getSecondCategory(req2).success(function (response) {
                    //把二级分类的data数组 赋值给view
                    $scope.$apply(function(){
                        if (type == "nation") {
                            $scope.Model.domesticCategory.dataClassify.content = response.data;
                        } else if (type == "intern") {
                            $scope.Model.internCategory.dataClassify.content = response.data;
                        }
                    });

                    if(!utils.isOwnEmpty($scope.curParams)){
                        var obj = {
                            scId : $scope.curParams.scId
                        };
                        var index = utils.getArrayIndex(response.data,obj,"scId");
                        $scope.clickCategory(obj,index);
                    }else {
                        getlist();
                    }
                })
            }).error(function () {
                console.log("请求失败！");
            })
        };

        //获取国际工程资料dcId 集合
        function getInterDcId(interDcId){
            var arr = [];
            for (var key in interDcId){
                if(interDcId[key]!=""){
                    arr.push(interDcId[key]);
                }
            }
            var dcId;
            dcId = arr.join(",");
            $scope.listParams.dcId = dcId;
            getlist();
        };
        /*
         * 加载国内 、国外数据 ， 参数
         * @type nation 表示国内  intern  表示国外
         * */
        $scope.curParams = {};
        function init (curParams){
            //搜索框搜索时 判断搜索关键词
            if(sessionStorage.hasOwnProperty("searchKeyWord")){
                $scope.listParams.keyWord = sessionStorage.searchKeyWord ;
            };
            //判断从外部点击进入 JSON.parse(string)
            if(sessionStorage.hasOwnProperty("engParams") && ((toString.call(sessionStorage.engParams)=="[object Object]")||(toString.call(sessionStorage.engParams)=="[object String]"))&&sessionStorage.engParams!="") {
                if(toString.call(sessionStorage.engParams)=="[object Object]"){
                    $scope.curParams =  sessionStorage.engParams;
                }
                if(toString.call(sessionStorage.engParams)=="[object String]"){
                    $scope.curParams =  JSON.parse(sessionStorage.engParams);
                }
                sessionStorage.removeItem('engParams');
                if($scope.curParams.tcId == 1){
                    loadData("nation");
                }else if($scope.curParams.tcId == 2){
                    loadData("intern");
                }
            }else{
                loadData("nation");
            }
        };

        init ();
        getDownLoadRank();
        getKeyWord();
        var indextemp;
        $scope.isShow = {
            showDataClassify: [],
            showFileType: [],

            //国内资料三级分类 显示flag
            showDetailClassify:[],

            //国际资料 三级分类 显示 flag
            showInterDetailClassify:{
                major:[],
                content:[],
                projectPattern:[]
            },
            showDetailBox:true,
            allUnderLine:false,
            allTypeUnderLine:false

        };

        //国际工程资料三级分类 专业 内容 项目模式 三类 点击“全部”  样式控制
        $scope.interDetailShow = {
            major:false,
            content:false,
            projectPattern:false
        };

        //重设工程资料蓝色样式标记
        function resetEngDataShow(){

            //国内
            //清空全部选项行为
            $scope.isShow.allUnderLine = true;
            //文件类型 全部
            $scope.listParams.typeId = 0;

            // 详情框默认展示
            $scope.isShow.showDetailBox = false;

            //初始化所有选中数据，这里只设置显示效果， 具体数据 在function  中判定。
            $scope.isShow.showDataClassify = [];
            $scope.isShow.showDetailClassify = [];
            $scope.isShow.showFileType = [];

            //国际
            $scope.interDetailShow = {
                major:false,
                content:false,
                projectPattern:false
            };
            $scope.isShow.showInterDetailClassify={
                major:[],
                content:[],
                projectPattern:[]
            }
        }

        //用于保存国际工程资料 三级分类dcId
        $scope.interDcId = {
            major:"",
            content:"",
            projectPattern:''
        };

        $scope.clickInterDeatilAllCategory = function(type){
            if(type!="major" && type!="content" && type!="projectPattern") return ;

            //蓝色显示该分类全部
            $scope.interDetailShow[type] = true;

            //正常显示 该分类“全部” 以外 其他子选项
            $scope.isShow.showInterDetailClassify[type] = [];

            //清空
            $scope.interDcId[type] = "";
            getInterDcId($scope.interDcId);

        };

        //点击国际三级分类
        $scope.clickInterDeatilCategory = function(item ,index,type){
            if(type!="major" && type!="content" && type!="projectPattern") return ;

            //正常显示该分类全部
            $scope.interDetailShow[type] = false;

            //蓝色显示 该分类“全部” 以外 其他子选项
            $scope.isShow.showInterDetailClassify[type] = [];
            $scope.isShow.showInterDetailClassify[type][index] =true;
            $scope.interDcId[type] = item.dcId;
            var dcName = item.dcName;
            getInterDcId($scope.interDcId ) ;
        };

        //切换国际工程资料 国内工程资料
        //选中a 标签 isCheckA = true;
        $scope.isCheckA = {
            intern: false,
            nation: true
        };

        $scope.changeEngData = function ( tcId) {

            //清楚默认显示
            resetEngDataShow();
            $scope.listParams.scId = null;
            if (tcId == 1) {
                loadData("nation");
            } else if (tcId == 2) {
                //点击国外工程资料 加载国外工程资料数据
                loadData("intern");
            }
        };

        //点击时间 下载 按照这两种方式显示不同的图标 列表图标 图片图标
        var dropAndSort = {
            drop:"them/img/bottom.png",
            sort :"them/imag/top-blue-arrow.png"
        };
        //当前scId  和 dcId  只有在点击detail Category 之后才会确定 。 点击国内三级
        $scope.clickDeatilCategory = function (detail,index) {
            if (!detail) {
                return
            }
            $scope.isShow.showDetailClassify = [];
            $scope.isShow.showDetailClassify[index] = true;
            $scope.listParams.dcId = detail.dcId;
            getlist();
        };

        //选择文件格式 “全部” 以外 其他选项
        $scope.curFileType = "";
        $scope.checkFileType = function (item,index) {
            $scope.isShow.allTypeUnderLine = false;
            $scope.isShow.showFileType = [];
            $scope.isShow.showFileType[index] = true;
            $scope.listParams.typeId = item.typeId;
            getlist();
        };

        // 选择文件格式  "全部"
        $scope.selectAllFileType = function(){
            $scope.isShow.showFileType = [];
            // 显示 全部下标线
            $scope.isShow.allTypeUnderLine = true;
            // 请求参数为  null 时  会在 ajax 请求 方法中过滤
            $scope.listParams.typeId = 0;
            getlist();
        };
        $scope.clickDataClassifyAll = function(){
            $scope.isShow.showDataClassify = [];
            $scope.isShow.showDetailBox = false;
            $scope.isShow.allUnderLine = true;
            $scope.tabcolor=1;
            //二级分类 为空
            $scope.listParams.scId = 0 ;
            getlist();
        };

        //点击搜索 搜索关键词
        $scope.searchKeyWord = function(){
            getlist();
        };

        //点击导航列表
        $scope.positionLeft = 0;

        $scope.isShow.showDataClassify = [];
        $scope.isShow.showDetailBox = false;
        $scope.isShow.allUnderLine = true;
        // 初始化 建筑位置 设置
        //  $scope.isShow.showDataClassify[0] = true;
        $scope.isShow.showDetailClassify[0] = true;
        // $scope.isShow.showFileType[0] = true;

        //点击二级目录
        $scope.clickCategory = function ( item, event) {
			$scope.tabcolor=2;
            //显示detail Box
            $scope.isShow.showDetailBox = true;

            //清除all 情况下的  下标线
            $scope.isShow.allUnderLine  =false;
            if(!!event){
                var  keyValue = event.srcElement ? 'srcElement' : 'target';
                var dis = event[keyValue].parentElement.offsetLeft - event[keyValue].parentElement.parentElement.offsetLeft;
                if (event[keyValue].parentElement.className == "f-engMain-cate-list clearfix" || event[keyValue].parentElement.className == "f-engMain-content-list ng-scope") {
                    return
                }
                $scope.positionLeft = dis + "px";
                $scope.triangleLeft = dis + "px";
            }
            if (!item) {
                return
            } else {
                var req = {
                    type: "GET",
                    data: {
                        scId: item.scId,
                        tcId: $scope.listParams.currentTcId
                    },
                    param: 'getDetailCategory'
                };
                $scope.listParams.scId = item.scId;

                //outerLoad  加载默认三级分类
                getDetailCategory(req).then(function(data){
                    /*
                    *  step 先清空 样式
                    * */
                    //清空显示下标线

                    //重置当前Detailbox 显示 分国际国内
                    if($scope.listParams.currentTcId == 1){
                        $scope.isShow.showDetailClassify = [];
                        $scope.isShow.showDetailClassify[0] = true;
                    }else if($scope.listParams.currentTcId == 2){
                        //重置国际工程资料dcId
                        $scope.interDcId = {
                            major:"",
                            content:"",
                            projectPattern:''
                        };
                    };
                    if(item.scId == 15){
                        $scope.major1 = "国家";
                        $scope.major2 = '专业';
                        $scope.major3 = '种类';
                    }else if(item.scId ==  16){
                        $scope.major1 = '专业';
                        $scope.major2 = '内容';
                        $scope.major3 = '项目模式';
                    }else if(item.scId == 17){
                        $scope.major1 = '经济环境';
                        $scope.major2 = '法律法规';
                        $scope.major4 = '宗教文化';
                        $scope.major3 = '合同管理';
                    }

                    /*
                     * 根据条件判断赋值
                     * */
                    if(! $scope.curParams){
                        return
                    }
                    //模拟点击三级事件
                    var detail = {
                        dcName:"",
                        dcId:$scope.curParams.dcId
                    };
                    if($scope.curParams.tcId == 1){
                        // 获取 下标
                        var objDc = {
                            dcId : $scope.curParams.dcId
                        };
                        var indexDc = utils.getArrayIndex(data,objDc,"dcId");
                        $scope.clickDeatilCategory(detail,indexDc);
                        $scope.curParams = null;
                    }else if($scope.curParams.tcId == 2){
                        //从第三方页面点击某一项 到该页面 三级分类只能选择一项
                        function fillDcid(obj){
                            if(toString.call(obj) !="[object Object]"){
                                return
                            };
                            var item  = {
                                dcId:$scope.curParams.dcId
                            };
                            for(var key in obj){
                                if( utils.isArrayContain(obj[key],item,"dcId")){
                                    $scope.interDcId[key] = item.dcId ;
                                }
                            }
                            $scope.listParams.dcId = $scope.curParams.dcId ;
                            getlist();
                            $scope.curParams = null;
                        };
                        fillDcid(data);
                    };

                });

            }
        };

        $scope.showA = function(index){
            $scope.isShow.showDataClassify = [];
            $scope.isShow.showDataClassify[index] = true;

        };
        $scope.mouseleave = function(index){
            //  $scope.isShow.showDataClassify[index] = false;
        };
        $scope.picSrc = {
            theTime:dropAndSort.drop,
            download:dropAndSort.drop,
            list:"them/img/tablist.png",
            pic:"them/img/tabpic.png"
        };

        var changeTime = function(){
            if($scope.picSrc.theTime ==dropAndSort.drop){
                $scope.picSrc.theTime =dropAndSort.sort
            }else{
                $scope.picSrc.theTime =dropAndSort.drop
            }
        };
        var changeDownload = function(){
            if($scope.picSrc.download ==dropAndSort.drop){
                $scope.picSrc.download =dropAndSort.sort
            }else{
                $scope.picSrc.download =dropAndSort.drop
            }
        };

        //根据时间排序
        $scope.sortByTime = function () {
            changeTime();
            $scope.listParams.time = !$scope.listParams.time;
            if ($scope.listParams.time && $scope.listParams.download) {
                $scope.listParams.download = false;
            }
            getlist();
        };
        //根据下载排序
        $scope.sortByDownload = function () {
            changeDownload();
            $scope.listParams.download = !$scope.listParams.download;
            if ($scope.listParams.time && $scope.listParams.download) {
                $scope.listParams.time = false;
            }
            getlist();
        };
        //点击工程名 进入工程详情页
        $scope.enterEngDetail = function (item) {
            var state = {
                state:"eng.techdetail"
            };
            $state.go(state.state,{fileId:item.fileId},{reload:true});
        };
        $scope.stateGo =function(state){
            $state.go("eng.uploadSelectFile");
        };

        // 点击资料 显示下拉框
        $scope.isShowData = false;
        $scope.isInList = false;
        $scope.clickData = function(){
            if($scope.isShowData == false){
                $scope.isShowData = true;
            }
        };
        $scope.leaveSearchList =function(){
            if($scope.isShowData == true){
                $scope.isShowData = false;
            }
            $scope.isInList = true;
        };
        //热搜词跳转
        $scope.jumpToSearch = function(item){
            $rootScope.GLOBALKEYWORD =  item.name;
            sessionStorage.searchKeyWord = item.name;
            $state.transitionTo("search.data", {}, {
                reload: true, inherit: false, notify: true
            });
        }


    })
});

